/*
 * @Author: ShiJunJie
 * @Date: 2021-01-11 15:43:12
 * @LastEditors: ShiJunJie
 * @LastEditTime: 2021-09-08 15:20:27
 * @Descripttion: 全局路由守卫
 */
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'

import storage from 'good-storage'

import { constantRouterMap, asyncRouterMap } from './routers/router.constant.js'

import { USER } from '/@/api/user'

const routes = [
  ...constantRouterMap // 管理端UI
  // ...asyncRouterMap
]

/**
 * createWebHistory()    history
 * createWebHashHistory()    hash
 */
const router = createRouter({
  // history: process.env.NODE_ENV === "development" ? createWebHashHistory() : createWebHistory(),
  history: createWebHashHistory(),
  routes
})

import { AllRoute } from './routers/allRouter.js'

// 配置NProgress进度条选项 —— 动画效果
NProgress.configure({ ease: 'ease', speed: 500, showSpinner: false })

const freeAccess = ['/user/login', '/404']

router.beforeEach((to, from, next) => {
  // 动态生成路由
  if (storage.get('USER_ROUTERS')) {
    storage.get('USER_ROUTERS').forEach((e, i) => {
      const newRoute = { ...e, component: AllRoute[e.component] }
      // console.log(e, newRoute, AllRoute[`${e.component}`])
      router.addRoute(newRoute)
    })
  }

  NProgress.start() // NProgress开始进度条
  console.log('路由监听', `from:${from.path}`, `to:${to.path}`)
  document.title = to.meta.title || to.name

  if (freeAccess.indexOf(to.path) !== -1) {
    console.log('非权限路由可访问')
    next()
  } else {
    if (!to.matched.length) {
      next('/404')
    } else {
      if (storage.get('USER_TOKEN')) {
        next()
      } else {
        console.log('用户未登录 请登录')
        next('/user/login')
      }
    }
  }
})
// 全局后置钩子-常用于结束动画等
router.afterEach((transition) => {
  NProgress.done() // NProgress结束进度条
  // console.log(transition)
})

export default router
